#include "stdafx.h"
#include "tabfile_center.h"

#include "baselib/LuaScript.h"

CTabFileCenter CTabFileCenter::ms_Instance;

CTabFileCenter::CTabFileCenter()
{

}

CTabFileCenter::~CTabFileCenter()
{

}

bool CTabFileCenter::Init(void)
{
	bool bResult = false;
	int nRetCode = 0;
	CLuaScript LuaScript;

	m_vecTabFile.clear();
	m_mapName2Index.clear();

	nRetCode = LuaScript.Init();
	LOG_PROCESS_ERROR(nRetCode);

	nRetCode = LuaScript.LoadFromFile("setting\\tabfile.lua");
	LOG_PROCESS_ERROR(nRetCode);

	lua_State* L = LuaScript.GetLuaState();
	LOG_PROCESS_ERROR(L);

	lua_getglobal(L, "TabFileTable");
	int nFileTable = lua_gettop(L);
	LOG_PROCESS_ERROR(lua_istable(L, nFileTable));

	int nFileCount = lua_objlen(L, nFileTable);
	m_vecTabFile.resize(nFileCount);
	m_vecTabFileConfig.resize(nFileCount);

	int nFileIndex = 0;
	lua_pushnil(L);
	while (lua_next(L, nFileTable))
	{
		int nFile = lua_gettop(L);
		LOG_PROCESS_ERROR(lua_istable(L, nFile));

		lua_getfield(L, nFile, "File");
		const char* pcszFileName = lua_tostring(L, -1);
		LOG_PROCESS_ERROR(pcszFileName);

		nRetCode = m_vecTabFile[nFileIndex].Init(pcszFileName);
		LOG_PROCESS_ERROR(nRetCode);

		lua_getfield(L, nFile, "Name");
		const char* pcszName = lua_tostring(L, -1);
		LOG_PROCESS_ERROR(pcszName);

		m_vecTabFileConfig[nFileIndex].strName = pcszName;
		m_vecTabFileConfig[nFileIndex].nStartRow = 1;
		m_mapName2Index[pcszName] = nFileIndex;

		nFileIndex++;
		lua_settop(L, nFile - 1);
	}

	bResult = true;
Exit0:

	nRetCode = LuaScript.UnInit();
	LOG_CHECK_ERROR(nRetCode);

	return bResult;
}

bool CTabFileCenter::UnInit(void)
{
	for (int nFileIndex = 0; nFileIndex < m_vecTabFile.size(); nFileIndex++)
	{
		m_vecTabFile[nFileIndex].UnInit();
	}

	m_vecTabFile.clear();
	m_mapName2Index.clear();

	return true;
Exit0:

	return false;
}

int CTabFileCenter::GetTabFileCount(void)
{
	return m_vecTabFile.size();
}

CTabFileEdit* CTabFileCenter::GetTabFile(int nIndex)
{
	LOG_PROCESS_ERROR(nIndex >= 0 && nIndex < m_vecTabFile.size());

	return &m_vecTabFile[nIndex];
Exit0:
	return NULL;
}

CTabFileEdit* CTabFileCenter::GetTabFile(const char* pcszTabName)
{
	std::map<std::string, int>::iterator it;

	it = m_mapName2Index.find(pcszTabName);
	LOG_PROCESS_ERROR(it != m_mapName2Index.end());

	return &m_vecTabFile[it->second];
Exit0:
	return NULL;
}

int CTabFileCenter::GetTabFileIndex(const char* pcszTabName)
{
	std::map<std::string, int>::iterator it;

	it = m_mapName2Index.find(pcszTabName);
	LOG_PROCESS_ERROR(it != m_mapName2Index.end());

	return it->second;
Exit0:
	return NULL;
}

TAB_FILE_CONFIG* CTabFileCenter::GetTabFileConfig(int nIndex)
{
	LOG_PROCESS_ERROR(nIndex >= 0 && nIndex < m_vecTabFileConfig.size());

	return &m_vecTabFileConfig[nIndex];
Exit0:
	return NULL;
}
